package com.itbaizhan.shopping_manager_api.security;

import com.itbaizhan.shopping_common.pojo.Admin;
import com.itbaizhan.shopping_common.pojo.Permission;
import com.itbaizhan.shopping_common.service.AdminService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author spf
 * @date 2023/12/17
 * @time 9:57
 */
@Service
public class MyUserDetails implements UserDetailsService {
    @Reference
    private AdminService adminService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 认证
        Admin admin = adminService.findByUsername(s);
        if(admin == null){
            throw new UsernameNotFoundException("用户不存在！");
        }

        // 授权
        List<Permission> permissionList = adminService.findAllPermissionByUsername(s);
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (Permission permission : permissionList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getUrl()));
        }

        // 封装成springsecurity user对象
        UserDetails userDetails = User.withUsername(admin.getUsername())
                .password(admin.getPassword())
                .authorities(grantedAuthorityList)
                .build();
        return userDetails;
    }
}
